package com.ileaf.chromosphere;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Lianlb
 * @since 2019-11-23 14:22
 */
public class ThreadPoolTest {

    private static int count = 0;

    public static void main(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(4, 10, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<>(200), new MyThreadFactory(), new MyRejectPolicy());
        for (int i = 1; i <= 100; i++) {
            executor.execute(new MyTask("" + i));
        }
        executor.shutdown();
        while (true) {
            if (executor.isTerminated()) {
                System.out.println("Result: " + count);
                return;
            }
        }
    }


    static class MyTask implements Runnable {
        private String name;

        public MyTask(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            System.out.println("线程" + Thread.currentThread() + "正在执行任务 - " + this);
            count++;
//            try {
//                Thread.sleep(3000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        @Override
        public String toString() {
            return "MyTask [name = " + name + "]";
        }
    }

    static class MyThreadFactory implements ThreadFactory {

        private AtomicInteger threadNumber = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "my-thread-" + threadNumber.getAndIncrement());
        }
    }

    static class MyRejectPolicy implements RejectedExecutionHandler {

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            System.err.println(r.toString() + " rejected");
//            throw new RejectedExecutionException("待处理任务超出线程队列最大值 - " + executor);
        }
    }

}
